
from sqlalchemy import and_

from exts import db
from flask import Blueprint, request, Response, jsonify, render_template, url_for, redirect, session


from dormitory.model import Dormitory


dormitory = Blueprint('dormitory', __name__);

# 宿舍列表
@dormitory.route('dormitory_list', methods=['GET', 'POST'])
def dormitory_list():
    dormitory_list = Dormitory.query.all()
    return render_template('dormitory_list.html', dormitory_list=dormitory_list)

# 学生名称 搜索
@dormitory.route('/dormitory/search', methods=['GET', 'POST'])
def search():
    keyword = request.args.get('keyword')
    dormitory_list = Dormitory.query.filter(
        Dormitory.student.like('%{keyword}%'.format(keyword=keyword))
    ).all()
    return render_template('dormitory_list.html', dormitory_list=dormitory_list)

# 删除宿舍信息
@dormitory.route('/dormitory/remove', methods=['GET', 'POST'])
def remove():
    id = request.args.get('id')
    dormitory = Dormitory.query.filter(
        Dormitory.id == id
    ).first()
    db.session.delete(dormitory)
    db.session.commit()
    return redirect(url_for('dormitory.dormitory_list'))

# 宿舍信息 详情，编辑，更新，添加
@dormitory.route('/dormitory/edit', methods=['GET', 'POST'])
def edit():
    if request.method=='GET':
        id = request.args.get('id')
        option = request.args.get('option')
        dormitory = Dormitory.query.filter(
            Dormitory.id == id
        ).first()
        if option == 'detail':
            return render_template('dormitory_editor.html', dormitory=dormitory)
        else:
            return render_template('dormitory_editor.html', dormitory=dormitory, update=True)
    else:
        id = request.form.get('id')
        lou = request.form.get('lou')
        name = request.form.get('name')
        student = request.form.get('student')
        phone = request.form.get('phone')

        dormitory = Dormitory.query.filter(
            Dormitory.id == id
        ).first()
        if dormitory is None:
            dormitory = Dormitory(lou=lou, name=name, student=student,phone=phone)
            db.session.add(dormitory)
            db.session.commit()
        else:
            dormitory.lou = lou
            dormitory.name = name
            dormitory.student = student
            dormitory.phone = phone
            db.session.commit()
        return redirect(url_for("dormitory.dormitory_list"))